import { createBrowserRouter, RouterProvider } from 'react-router-dom'
import { routes } from './router'
import { useDispatch, useSelector } from 'react-redux'
import { Suspense, useEffect, useState } from 'react'
import { generateRoute } from './utils/generateRoute.tsx'
import { getMenu } from './api/users.ts'
import { convertToMenuItem } from './type/menu.ts'
import { setRouterMenuList } from './store/login/authSlice.ts'

function App() {
  const dispatch = useDispatch()
  const [routers, setRouters] = useState<any>(null)
  const { token } = useSelector((state: any) => state.authSlice)

  useEffect(() => {
    // 浏览器刷新时，整个react应用会重新初始化，redux store也会重新创建，所以menulist数据会没有了，导致menulist为空
    // menulist为空，当我们继续使用/dashboard进行请求时，路由中没有此路径且没有对应的组件，所以就会返回页面找不到
    async function loadMenu() {
      const { data } = await getMenu()
      if (data) {
        const menuItems = convertToMenuItem(data)
        dispatch(setRouterMenuList(menuItems))
        const routeFromApi = generateRoute(menuItems)
        const myRoutes = [...routes]
        myRoutes[0].children = routeFromApi
        if (myRoutes[0].children && myRoutes[0].children.length > 0) {
          myRoutes[0].children[0].index = true
        }
        const router = createBrowserRouter(myRoutes)
        setRouters(router)
      } else {
        const router = createBrowserRouter(routes)
        setRouters(router)
      }
    }

    loadMenu()
  }, [token])

  if (!routers) {
    return null
  }

  return (
    <Suspense>
      <RouterProvider router={routers} />
    </Suspense>
  )
}

export default App
